/**
 * Copyright (c) 2017, Alex. All rights reserved.
 */
package com.oschina.bottle.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * HttpServletRequest、HttpServletResponse 数据处理
 *
 * @author <a href="mailto:zhongchao@gegejia.com">zhong</a>
 * @version 1.0 2017/9/27
 * @since 1.0
 */
public class HttpUtils
{
    private static final String CONTENT_TYPE_JSON = "application/json;charset=UTF-8";

    /**
     * 获取ipV4地址
     *
     * @param request
     * @return
     */
    public static String getRemoteIpAddr(HttpServletRequest request)
    {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr();
        }
        if (ip != null && ip.length() > 15)
        {
            if (ip.indexOf(",") > 0)
            {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }

    /**
     * 设置cookie
     * @param response
     * @param name  cookie名字
     * @param value cookie值
     * @param maxAge cookie生命周期  以秒为单位
     */
    public static void addCookie(HttpServletResponse response, String domain, String name, String value, int maxAge)
    {
        try
        {
            Cookie cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));

            if (!StringUtils.isBlank(domain))
            {
                cookie.setDomain(domain);
            }
            cookie.setPath("/");

            if (maxAge >= 0)
            {
                cookie.setMaxAge(maxAge);
            }

            response.addCookie(cookie);
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 根据名字获取cookie
     * @param request
     * @param name cookie名字
     * @return Cookie对象
     */
    public static Cookie getCookieByName(HttpServletRequest request, String name)
    {
        Cookie[] cookies = request.getCookies();
        if (null != cookies)
        {
            for (Cookie cookie : cookies)
            {
                if (cookie.getName().equals(name))
                {
                    return cookie;
                }
            }
        }
        return null;
    }

    /**
     * 根据名字获取cookie VALUE
     * @param request
     * @param name cookie名字
     * @return Cookie对象
     */
    public static String getCookieValueByName (HttpServletRequest request,String name) {
        Cookie cookie = getCookieByName(request, name);
        if(cookie != null) {
            return cookie.getValue();
        }
        return null;
    }

    /**
     * 更新单个cookie（有效时间和值）
     *
     * @param response
     * @param maxAge
     * @param cookie
     */
    public static void updateCookie(HttpServletResponse response, int maxAge, String value, Cookie cookie) {
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        cookie.setValue(value);
        response.addCookie(cookie);
    }

    /**
     * 更新单个cookie（有效时间）
     *
     * @param response
     * @param maxAge
     * @param cookie
     */
    public static void updateCookie(HttpServletResponse response, int maxAge, Cookie cookie) {
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    /**
     * 更新多个cookie（有效时间）
     *
     * @param response
     * @param maxAge
     * @param cookies
     */
    public static void updateCookies(HttpServletResponse response, int maxAge, Cookie ... cookies) {
        for (Cookie cookie : cookies) {
            updateCookie(response, maxAge, cookie);
        }
    }

    /**
     * 提取request中的所有请求参数
     *
     * @param request
     * @return
     */
    public static String getParam(HttpServletRequest request)
    {
        Map<String, String[]> params = request.getParameterMap();
        if(MapUtils.isEmpty(params)) {
            return "";
        }

        List<String> paramList = new ArrayList<>();

        for(Map.Entry<String, String[]> entry : params.entrySet()) {
            paramList.add(String.format("%s=%s", entry.getKey(), StringUtils.join(entry.getValue())));
        }
        return StringUtils.join(paramList, ";");
    }
}
